<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 云元类别
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container v2-group">
            <div class="handle-box">
                <el-input v-model="query.title" placeholder="名称" class="handle-input mr10" clearable></el-input>
                <el-input v-model="query.code" placeholder="编码" class="handle-input mr10" clearable></el-input>
                <!-- <el-input v-model="query.tableName" placeholder="表名" class="handle-input mr10" clearable></el-input>
                <el-input v-model="query.tablePrefix" placeholder="表前缀名" class="handle-input mr10" clearable></el-input> -->
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
                <el-button
                    type="success"
                    icon="el-icon-plus"
                    class="handle-del mr10"
                    @click="handleAdd"
                >新增</el-button>
                <!-- <el-tooltip content="生成代码" placement="bottom" effect="light">
                    <el-button type="primary" icon="el-icon-message" @click="developAllSelection" circle></el-button>
                </el-tooltip> -->
            </div>
            <!-- default-expand-all -->
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
                stripe
                :tree-props="{children: 'children'}"
                row-key="id"
            >
                <!-- <el-table-column type="selection" width="55" align="center"></el-table-column> -->
                <el-table-column prop="title" label="名称" show-overflow-tooltip></el-table-column>
                <el-table-column prop="code" label="编码" width="180"></el-table-column>
                <el-table-column prop="description" label="含义" show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" width="210">
                    <template slot-scope="scope">
                        <!-- <el-button
                            type="text"
                            icon="el-icon-plus"
                            @click="handleCopy(scope.$index, scope.row)"
                        >复制</el-button> -->
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, sizes, prev, pager, next, jumper"
                    :current-page="query.current"
                    :page-size="query.size"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                    :page-sizes="[10, 20, 30, 40, 50, 100]"
                    @size-change="handleSizeChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
            <el-form ref="entityEdit" :model="form" :rules="rulesEntityEdit" label-width="70px">
                <el-form-item label="名称" prop="title">
                    <el-input v-model="form.title"></el-input>
                </el-form-item>
                <el-form-item label="编码" prop="code">
                    <el-input v-model="form.code" placeholder="(sysrun,terminal,其他)"></el-input>
                </el-form-item>  
                <el-form-item label="上级类别" prop="parentId">
                    <el-popover
                        placement="bottom"
                        :trigger="listParent.length ? 'click' : 'manual'">
                        <div class="pop-content">
                            <div>
                                <el-tree :data="listParent" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
                            </div>
                        </div>
                        <el-input slot="reference" v-model="form.parentName"></el-input>
                    </el-popover>
                </el-form-item> 
                <el-form-item label="含义" prop="description">
                    <el-input v-model="form.description" type="textarea" autosize></el-input>
                </el-form-item> 
                <el-form-item label="介绍" prop="path">
                    <el-input v-model="form.path" type="textarea" autosize></el-input>
                </el-form-item> 
                <el-form-item label="功用类型" prop="featureType">
                    <el-input v-model="form.featureType" placeholder="(文本,图片集,视频,短消息,商品资产)"></el-input>
                </el-form-item>  
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 新增弹出框 -->
        <el-dialog title="新增" :visible.sync="addVisible" width="30%">
            <el-form ref="entityAdd" :model="form" :rules="rulesEntityAdd" label-width="70px">
                <el-form-item label="名称" prop="title">
                    <el-input v-model="form.title"></el-input>
                </el-form-item>
                <el-form-item label="编码" prop="code">
                    <el-input v-model="form.code" placeholder="(sysrun,terminal,其他)"></el-input>
                </el-form-item>  
                <el-form-item label="上级类别" prop="parentId">
                    <el-popover
                        placement="bottom"
                        :trigger="listParent.length ? 'click' : 'manual'">
                        <div class="pop-content">
                            <div>
                                <el-tree :data="listParent" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
                            </div>
                        </div>
                        <el-input slot="reference" v-model="form.parentName"></el-input>
                    </el-popover>
                </el-form-item> 
                <el-form-item label="含义" prop="description">
                    <el-input v-model="form.description" type="textarea" autosize></el-input>
                </el-form-item> 
                <el-form-item label="介绍" prop="path">
                    <el-input v-model="form.path" type="textarea" autosize></el-input>
                </el-form-item> 
                <el-form-item label="功用类型" prop="featureType">
                    <el-input v-model="form.featureType" placeholder="(文本,图片集,视频,短消息,商品资产)"></el-input>
                </el-form-item> 
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import api from '../../../api/index';
import sysdict from '../../../api/sysdict';

export default {
    name: 'basetable',
    data() {
        return {
            query: {
                title: '',
                code: '',
                current: 1,
                size: 10
            },
            tableData: [
                {
                    username: 'user01',
                    surname: '张三',
                    user_group: '普通用户',
                    last_login: '2024-11-01 00:00:00',
                    status: '正常'
                }
            ],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            addVisible: false,
            roles: [],
            rulesEntityAdd: {
                // category: [{ required: true, message: '请选择岗位类型', trigger: 'change', type: 'integer' }],
                title: [{ required: true, message: '请输入名称', trigger: 'blur' }],
                code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
                description: [{ required: true, message: '请输入含义', trigger: 'blur' }]
            },
            rulesEntityEdit: {
                code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
                appInfoName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
                appInfoMeaning: [{ required: true, message: '请输入含义', trigger: 'blur' }],
                appInfoIntroduction: [{ required: true, message: '请输入介绍', trigger: 'blur' }]
            },
            sysdict,
            listParent: [],
            defaultProps: {
                children: 'children',
                label: 'title'
            }
        };
    },
    created() {
        this.getData();
    },
    methods: {
        // 获取 easy-mock 的模拟数据
        getData() {
            api.getCategoryList(this.query).then(res => {
                this.tableData = res;
                this.pageTotal = res.length;
            }).catch(err => {
                this.$message.error(err);
            });
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'current', 1);
            this.getData();
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
            .then(() => {
                api.deleteCategory({ids: row.id}).then(res => {
                    this.$message.success('删除成功');
                    this.getData();
                }).catch(err => {
                    this.$message.error(err);
                });
            })
            .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        developAllSelection() {
            this.$confirm('确定要生成代码吗？', '提示', {
                type: 'warning'
            })
            .then(() => {
                const length = this.multipleSelection.length;
                let str = '';
                var arr = [];
                for (let i = 0; i < length; i++) {
                    str += this.multipleSelection[i].name + ' ';
                    arr.push(this.multipleSelection[i].id);
                }
                // this.$message.error(`删除了${JSON.stringify(arr)}`);
                api.runDevelop({ids: arr}).then(res => {
                    this.$message.success('生成成功');
                }).catch(err => {
                    this.$message.error(err);
                });
            })
            .catch(() => {});
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form = Object.assign({}, row);
            this.editVisible = true;
            this.prepareForm();
        },
        // 保存编辑
        saveEdit() {
            this.$refs.entityEdit.validate(valid => {
                if (valid) {
                    api.saveCategory(this.form).then(res => {
                        this.editVisible = false;
                        this.$message.success(`修改第 ${this.idx + 1} 行成功`);
                        // this.$set(this.tableData, this.idx, this.form);
                        this.getData();
                    }).catch(err => {
                        this.$message.error(err);
                    });
                } else {
                    return false;
                }
            });
        },
        // 新增操作
        handleAdd() {
            this.form = {};
            this.addVisible = true;
            this.prepareForm(true);
        },
        saveAdd() {
            this.$refs.entityAdd.validate(valid => {
                if (valid) {
                    api.saveCategory(Object.assign({}, this.form, {datasourceId: '1123598812738675201', baseMode: 1, wrapMode: 1})).then(res => {
                        this.$message.success(`新增成功`);
                        this.addVisible = false;
                        this.getData();
                    }).catch(err => {
                        this.$message.error(err);
                    });
                } else {
                    return false;
                }
            });
        },
        handleCopy(index, row) {
            this.idx = index;
            this.form = Object.assign({}, row);
            delete this.form.id;
            this.addVisible = true;
            this.prepareForm();
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'current', val);
            this.getData();
        },
        handleSizeChange(val) {
            this.$set(this.query, 'size', val);
            this.getData();
        },
        prepareForm(addNew) {
            api.getCategoryTree({}).then(res => {
                this.listParent = res;
                if (this.form.parentId) {
                    this.getParentName(this.listParent);
                }
            }).catch(err => {
                this.$message.error(err);
            });
            // if (!addNew) {
            //     api.getDepartmentDetail({id: this.form.id}).then(res => {
            //         this.form = res;
            //     }).catch(err => {
            //         this.$message.error(err);
            //     });
            // }
        },
        handleNodeClick(data) {
            this.form.parentId = data.id;
            this.form.parentName = data.title;
            this.$forceUpdate();
            // this.$message.info(this.form.parentName);
        },
        getParentName(list) {
            var that = this;
            var arr = list.filter(e => e.key === that.form.parentId);
            if (arr.length) {
                that.form.parentName = arr[0].title;
            }
            else {
                list.forEach(e => {
                    if (e.children.length) {
                        that.getParentName(e.children);
                    }
                });
            }
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.pop-content > div {
    width: 30vw;
    display: flex;
    flex-wrap: wrap;
}
.pop-content > div .el-tree {
    width: 100%;
}
</style>
